package top.milkbox.api.BaiduTranslationApi;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import top.milkbox.info.BaiduTranslationInfo.BaiduTranslationInfo;
import top.milkbox.info.BaiduTranslationInfo.TranslationSuccessResult;

import java.util.HashMap;
import java.util.Map;

@Component
public class BaiduTransApi {
    private String host;

    private String appid;
    private String securityKey;

    @Autowired
    private RestTemplate restTemplate;

    public BaiduTransApi(@Autowired BaiduTranslationInfo info) {
        this.appid = info.getAppid();
        this.securityKey = info.getSecret();
        this.host = info.getUrl();
    }

    /**
     * 发送翻译请求
     *
     * @param query 翻译内容
     * @param from  源语言
     * @param to    目标语言
     * @return 返回对象
     */
    public TranslationSuccessResult getTransResult(String query, String from, String to) {
        Map<String, String> params = buildParams(query, from, to);
        // 将参数预拼接
        String url = host + "?q=" + params.get("q") +
                "&from=" + params.get("from") +
                "&to=" + params.get("to") +
                "&appid=" + params.get("appid") +
                "&salt=" + params.get("salt") +
                "&sign=" + params.get("sign");
        return restTemplate.getForObject(url, TranslationSuccessResult.class);
    }

    private Map<String, String> buildParams(String query, String from, String to) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("q", query);
        params.put("from", from);
        params.put("to", to);

        params.put("appid", appid);

        // 随机数
        String salt = String.valueOf(System.currentTimeMillis());
        params.put("salt", salt);

        // 签名
        String src = appid + query + salt + securityKey; // 加密前的原文
        params.put("sign", MD5.md5(src));

        return params;
    }

}
